package com.sxran.im.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxran.im.bean.ImException;
import com.sxran.im.bean.LoginReqBody;
import com.sxran.im.dao.ImGroupMapper;
import com.sxran.im.dao.ImUserGroupMapper;
import com.sxran.im.dao.ImUserMapper;
import com.sxran.im.info.ImGroup;
import com.sxran.im.info.ImUser;
import com.sxran.im.info.ImUserGroup;
import com.sxran.im.service.JWTService;
import com.sxran.im.service.UserGroupService;
import com.sxran.im.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LoginCmdHandler extends AbstractCmdHandler<LoginReqBody>{
    private Logger logger = LoggerFactory.getLogger(LoginCmdHandler.class);

    @Resource
    private ImUserMapper imUserMapper;
    @Resource
    private ImGroupMapper imGroupMapper;

    @Resource
    private UserGroupService userGroupService;

    @Resource
    private UserService userService;
    @Resource
    private JWTService jwtService;
    @Override
    public Object doBeanService(LoginReqBody bean) {
        // token 校验里面的内容。 自行编写里面的校验逻辑。
        String token = bean.getToken();
        String userId = bean.getUserId();
        // 校验token内容。
        if( !jwtService.verify(token) || !StrUtil.equals(jwtService.getUserId(token),userId) ){
            throw new ImException("token校验失败",10008);
        }
        // 获得里面用户信息。
        ImUser imUser = userService.selectByUserId(userId);

//        String userId = imUser.getUserId();
//        // 用户基本信息
//        ImUser imUser = imUserMapper.selectById(userId);
//        // 朋友
//        List<ImGroup> friends = new ArrayList<>();
//        imUser.setFriends(friends);
        // 群组
        List<ImUserGroup> imUserGroups = userGroupService.selectList(userId);
        //
        List<ImGroup> groups = imUserGroups.stream().map(x -> imGroupMapper.selectById(x.getGid())).collect(Collectors.toList());
        imUser.setGroups(groups);
        // 设置状态为上线。
        imUser.setStatus(0);
        imUserMapper.updateById(imUser);
        return imUser;
    }
}
